package pers.tz.题目.leetcode.树;

import pers.tz.common.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @author irony
 * @date 2024-03-13
 */
public class leetcode_0145_二叉树的后序遍历 {
    public static void main(String[] args) {

    }

    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        traversal(ans, root);

        return ans;
    }

    private static void traversal(List<Integer> ans, TreeNode root) {
        if (root == null) {
            return;
        }

        traversal(ans, root.left);
        traversal(ans, root.right);
        ans.add(root.val);
    }

    // 迭代方式
    public List<Integer> postorderTraversal2(TreeNode root) {
        List<Integer> ans = new ArrayList<>(); // 左 右 头
        if (root == null) {
            return ans;
        }

        Stack<TreeNode> stack1 = new Stack<>(); // 左 右
        Stack<TreeNode> stack2 = new Stack<>(); // 头 右 左

        stack1.push(root);
        while (!stack1.isEmpty()) {
            TreeNode head = stack1.pop();
            stack2.push(head);

            if (head.left != null) {
                stack1.push(head.left);
            }
            if (head.right != null) {
                stack1.push(head.right);
            }
        }

        while (!stack2.isEmpty()) {
            ans.add(stack2.pop().val);
        }

        return ans;
    }
}
